package ranab.jar.view;

import java.text.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.tree.*;

/**
 * Tree node - represents a <code>ZipEntry</code>.
 *
 * @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
 */

public
class TreeNode extends Vector {
	
	private String mstAbsPath;
	private String mstName;
	private TreeNode mParent;
	private ZipEntry mEntry;
	
	/**
	 * Constructor
	 */
	public TreeNode(TreeNode parent, 
	                  String fileName, 
					  ZipEntry entry)  {
		mstName = fileName;
		mParent = parent;
		mEntry = entry;
		if (parent == null)  {
			mstAbsPath = mstName; 
		}
		else  {
			mstAbsPath = parent.getAbsolutePath() + '/' + mstName;
		    parent.add(this);
        }
	}
	
	/**
	 * Get node.
	 */
	public TreeNode getNode(String nodeAbsName)  {
		int index = indexOf(nodeAbsName);
		if (index == -1)  {
			return null;
		}
		return (TreeNode)get(index);
	} 
	
	/**
	 * Index of a particular string node.
	 */
	public int indexOf(String nodeAbsName)  {
		for(int i=0; i<size(); i++)  {
			TreeNode node = (TreeNode)get(i);
			if (node.mstAbsPath.equals(nodeAbsName))  {
				return i;
			}
		}
		return -1;
	}
	
    /**
     * Index of a particular node.
     */
	public int indexOf(TreeNode cnode)  {
		for(int i=0; i<size(); i++)  {
			TreeNode node = (TreeNode)get(i);
			if (node.mstAbsPath.equals(cnode.mstAbsPath))  {
				return i;
			}
		}
		return -1;
	}
	
	
	
	/**
	 * Clear all nodes.
	 */
	public void clear()  {
		Iterator listIt = listIterator(0);
		while (listIt.hasNext())  {
			TreeNode nd = (TreeNode)listIt.next();
			nd.clear();
		}
        super.clear();
	}
	
	/**
	 * Get parent node.
	 */
	public TreeNode getParent()  {
		return mParent;
	}
	
     
	/**
	 * Is a folder?
	 */
	public boolean isLeaf()  {
		if (mEntry == null)  {
			return false;
		}
		return (size() == 0) && (!mEntry.isDirectory());
	}
	
	/**
	 * Get entry - if not a leaf returns null.
	 */
	public ZipEntry getEntry()  {
		if (isLeaf())  {
			return mEntry;
		}
		return null;
	}
	
	/**
	 * Get absolute path.
	 */
	public String getAbsolutePath()  {
		return mstAbsPath;
	}
	
	
	/**
	 * Check equality.
	 */
	public boolean equals(Object obj)  {
		
		// check object
		if (obj == null)  {
			return false;
		}
		if (!(obj instanceof ranab.jar.view.TreeNode))  {
			return false;
		}
		
		TreeNode nd = (TreeNode)obj;
		return mstAbsPath.equals(nd.mstAbsPath);
	}
	
	/**
	 * Get the directory name
	 */
	public String toString()  {
		return mstName;
	}
}